/**
 * @name Fw.ListView
 * @class 列表组件
 * @constructor
 * @example
 * @return
 */
Fw.ListView = Fw.extend(Fw.Component, {
    //行号默认宽度
    rowNumber: {
        width: 10,
        style: ''
    },
    //显示斑马线
    stripeRows: true,
    //行选中样式
    selectedItemCls: null,
    //
    itemCls: 'item',
    /**
     * 初始化组件
     */
    initComponent : function() {
        Fw.ListView.superclass.initComponent.call(this);
        //
        this.initItemTpl();
        //新建ajax工具类
        this.ajax = new Fw.Ajax(this.ajax);
        //初始化翻页
        if(this.ajax.page !== false){
            this.el.addClass('paging');
            if(this.ajax.simplePage){
                //简单分页（只显示上一页、下一页）
                this.pagingTb = new Fw.SimplePaging({
                    owner: this
                });
            }
            else{
                this.pagingTb = new Fw.Paging({
                    owner: this
                });
            }
        }
    },
    /**
     * 初始化事件
     */
    initEvents : function() {
        this.ajax.on('query', this.onLoadData, this);
        this.tbody.on('click', 'tr.item', Fw.bind(this.doSelect, this));
    },
    /**
     * 初始化HTML模版
     */
    initTpl : function() {
        var id = Fw.id();
        var tpl = ['<tbody id="${id}-tbody"></tbody>'];
        this.el.append(Fw.template(tpl, {
            id : id
        }));
        this.tbody = $('#' + id + '-tbody');
    },
    /**
     * 初始化ITEM模版
     */
    initItemTpl : function() {
        var itemTpl = [];
        itemTpl.push('{@each data as item}');
        // itemTpl.push('{@if onItemAdd(item, index)}');//
        itemTpl.push('<tr class="item" _index="${index}" _page="${page}">');
        if(this.rowNumber){
            if(Fw.isObject(this.rowNumber)){
                Fw.applyIf(this.rowNumber, Fw.ListView.prototype.rowNumber);
            }
            else{
                this.rowNumber = Fw.apply({}, Fw.ListView.prototype.rowNumber);
            }
            itemTpl.push('<td width="${rowNumber.width}" style="${rowNumber.style}">${rowNumber.number}.</td>');
        }
        Fw.each(this.itemTpl, function(item){
            itemTpl.push(item);
        });
        itemTpl.push('</tr>');
        // itemTpl.push('{@/if}');
        itemTpl.push('{@/each}');
        //
        // itemTpl.push({
            // rownumber: Fw.bind(function(index){
                // return (index*1 + (this.ajax.currentPage - 1) * this.ajax.pageSize + 1) + '.';
            // }, this),
            // onItemAdd: Fw.bind(this.onItemAdd, this)
        // });
        this.itemTpl = Fw.template(itemTpl);
    },
    /**
     * 选中记录
     */
    doSelect: function(e){
        var el = $(e.target);
        var item = el.parents('tr.item');
        var index = item.attr('_index') * 1;// + (item.attr('_page') - 1) * this.ajax.pageSize;
        if(this.selectedItemCls){
            if(this.oldItem && (this.oldItem.attr('_index') * 1) !== index){
                this.oldItem.removeClass(this.selectedItemCls);
            }
            if(!item.hasClass(this.selectedItemCls)){
                item.addClass(this.selectedItemCls);
            }
        }
        this.oldItem = item;
        this.fireEvent('itemclick', this.data[index], index, item, e, this);
    },
    /**
     * 载入数据
     * @param {} page
     */
    loadData: function(page){
        this.ajax.query(Fw.isNumber(page) ? page || 1 : 1);
    },
    /**
     * 载入数据后触发
     * @param {} ajax
     * @param {} data
     */
    onLoadData : function(ajax, data) {
    	//sm指定分页数，手动更新当前分页信息
    	//sm指定分页数，手动更新当前分页信息
        if(!this.ajax.simplePage && this.ajax.page !== false && this.refreshPage !== true){
        	this.pagingTb.refresh(true);
        	this.refreshPage = true;
        }
        //sm指定分页数，手动更新当前分页信息
        
        this.data = data;
        //将HTML渲染到页面
        if(data && data.length > 0 ){
            var html = '';
            Fw.each(data, function(item, index){
                if(this.fireEvent('beforeitemadd', item, index, this) !== false){
                    html = this.itemTpl.render({
                        data: [item],
                        page: this.ajax.currentPage,
                        rowNumber: Fw.apply(this.rowNumber, {
                            number: index*1 + (this.ajax.currentPage - 1) * this.ajax.pageSize + 1
                        }),
                        index: index
                    });
                    this.tbody[index === 0 ? 'html' : 'append'](html);
                    
                }
            }, this);
            
            // this.tbody.html(this.itemTpl.render({
                // data: data,
                // page: this.ajax.currentPage
            // }));
        }
        else{
            this.tbody.html('');
        }
    }
});

/**
 * @name Fw.Paging
 * @class 分页组件
 * @constructor
 * @example
 * @return
 */
Fw.Paging = Fw.extend(Fw.Component, {
    emptyMsg: '没有数据',
    /**
     * 初始化组件
     */
    initComponent : function() {
        this.ajax = this.owner.ajax;
        Fw.Paging.superclass.initComponent.call(this);
    },
    /**
     * 初始化事件
     */
    initEvents : function() {
        this.ajax.on('query', this.refresh, this);
        this.el.on('click', 'a', Fw.bind(this.onClick, this));
    },
    /**
     * 初始化HTML模版
     */
    initTpl : function() {
        var id = this.owner.el.attr('id');
        var colspan = 20;//?
        var tpl = [];
        //
        this.pagingItems = {
            id: id,
            first: Fw.id(),
            prev: Fw.id(),
            next: Fw.id(),
            last: Fw.id(),
            pageInfo: Fw.id(),
            displayInfo: Fw.id(),
            pageLimit: this.ajax.pageLimit,
            colspan : colspan
        };
        //
        tpl.push('<tfoot id="tfoot-paging">');
        tpl.push('<tr>');
        tpl.push('<td id="${id}-paging" class="paging-body" colspan="${colspan}" width="100%" nowrap>');
        ////
        tpl.push('<a id="${last}" page="last" title="最后${pageLimit}页">»</a>');
        tpl.push('<a id="${next}" page="next" title="后${pageLimit}页">›</a>');
        var pageNo, pageId;
        for(var i=this.ajax.pageLimit-1; i>=0; i--){
            pageNo = i + 1;
            pageId = this.pagingItems['page' + pageNo] = Fw.id();
            tpl.push(
                Fw.template('<a id="${pageId}" page="${pageNo}" style="display: none;" title="第${pageNo}页">${pageNo}</a>', {
                    pageId: pageId,
                    pageNo: pageNo
                })
            );
        }
        tpl.push('<a id="${prev}" page="prev" title="前${pageLimit}页">‹</a>');
        tpl.push('<a id="${first}" page="first" title="最前${pageLimit}页">«</a>');
        tpl.push('<span id="${displayInfo}" class="displayInfo"></span>');
        //
        tpl.push('</td>');
        tpl.push('</tr>');
        tpl.push('</tfoot>');
        this.owner.el.append(Fw.template(tpl, this.pagingItems));
        this.el = $('#' + id + '-paging');
        this.displayInfo = $('#' + this.pagingItems.displayInfo);
    },
    /**
     * 更新分页信息 
     */
    update: function(){
        var isEmpty = this.pageData.total === 0;
        var item, page;
        for(var p in this.pagingItems){
            item = $('#' + this.pagingItems[p]);
            if(!item || !item.attr('page')) continue;
            switch(p) {
                case 'first':
                    item[this.ajax.currentPages === 1 || isEmpty ? 'addClass' : 'removeClass']('disable');
                    break;
                case 'prev':
                    item[this.ajax.currentPages === 1 || isEmpty ? 'addClass' : 'removeClass']('disable');
                    break;
                case 'next':
                    item[this.pageData.pagesCount <= this.ajax.currentPages || isEmpty ? 'addClass' : 'removeClass']('disable');
                    break;
                case 'last':
                    item[this.pageData.pagesCount <= this.ajax.currentPages || isEmpty ? 'addClass' : 'removeClass']('disable');
                    break;
                default:
                    page = item.attr('page') * 1;
                    if(this.movePages){
                        page += (this.ajax.currentPages - this.ajax.beforePages) * this.ajax.pageLimit;
                        item.attr('page', page);
                        //item.attr('title', '第' + page + '页');
                        item.attr('data-original-title', '第' + page + '页');
                        item.html(page);
                    }
                    item[page === this.ajax.currentPage ? 'addClass' : 'removeClass']('selected');
                    item[page > this.pageData.pageCount ? 'hide' : 'show']();
                    break;
            }
        }
        //
        var msg;
        if(isEmpty){
            msg = this.emptyMsg;
        }
        else{
            msg = '显示 ' + this.pageData.start + ' - ' + this.pageData.end + ' 条，共 ' + this.pageData.total + ' 条 / ' + this.pageData.pageCount + ' 页';
        }
        this.displayInfo.html(msg);
        //
        this.movePages = false;
        //
        if(!Fw.isTouch && page === 1){
            this.el.find('[title]').tooltip({
                placement: 'auto'
            });
        }
    },
    /**
     * 刷新分页信息
     */
    refresh: function(pageIdent){
        var totalCount = this.ajax.totalCount;
        this.pageData = {
            total: totalCount,
            pageCount: Math.ceil(totalCount / this.ajax.pageSize),
            pagesCount: Math.ceil(totalCount / this.ajax.pageSize / this.ajax.pageLimit),
            start: ((this.ajax.currentPage - 1) * this.ajax.pageSize) + 1,
            end: Math.min(this.ajax.currentPage * this.ajax.pageSize, totalCount)
        };
        
        var queryParams = Fw.encode(this.ajax.getParams());
        if(this.lastQueryParams && this.lastQueryParams !== queryParams){
            //查询条件改变后，默认跳转到第一页
            this.ajax.currentPage = 1;
            this.ajax.beforePages = this.ajax.currentPages;
            this.ajax.currentPages = 1;
            this.movePages = true;
        }
        this.lastQueryParams = queryParams;
        //sm 如果指定分页并且不是默认5页，显示当前分页信息
        if(pageIdent === true && this.ajax.currentPage > this.ajax.pageLimit){
        	this.loadPage(this.ajax.currentPage);
        	this.movePages = true;
        }
        //sm 如果指定分页并且不是默认5页，显示当前分页信息
        this.update();
    },
    /**
     * 分页工具条单击事件
     */
    onClick: function(e){
        var el = $(e.target);
        if(el && !el.hasClass('disable')){
            var page = el.attr('page');
            switch(page) {
                case 'first':
                    this.moveFirst();
                    break;
                case 'prev':
                    this.movePrevious();
                    break;
                case 'next':
                    this.moveNext();
                    break;
                case 'last':
                    this.moveLast();
                    break;
                default:
                    this.loadPage(page * 1);
                    this.movePages = false;
                    break;
            }
        }
    },
    /**
     * 移动到第一页
     */
    moveFirst: function(){
        this.loadPage(1);
    },
    /**
     * 移动到上10页
     */
    movePrevious: function(){
        var prev = (this.ajax.currentPages - 1) * this.ajax.pageLimit - this.ajax.pageLimit + 1;
        if (prev > 0) {
            this.loadPage(prev);
        }
    },
    /**
     * 移动到下10页
     */
    moveNext: function(){
        if(!this.pageData) return;
        var total = this.pageData.pageCount;
        var next = this.ajax.currentPages * this.ajax.pageLimit + 1;
        if (next <= total) {
            this.loadPage(next);
        }
    },
    /**
     * 移动到最后一页
     */
    moveLast : function(){
        if(!this.pageData) return;
        var last = this.pageData.pagesCount * this.ajax.pageLimit - this.ajax.pageLimit + 1;
        this.loadPage(last);
    },
    /**
     * 分页
     * @param {Object} page
     */
    loadPage: function(page){
        if(!this.pageData) return;
        if (this.fireEvent('beforechange', this, page) !== false) {
            this.ajax.currentPage = page;
            this.ajax.beforePages = this.ajax.currentPages;
            this.ajax.currentPages = Math.ceil(page / this.ajax.pageLimit);
            this.movePages = true;
            this.ajax.query(page);
        }
    }
});

/**
 * @name Fw.SimplePaging
 * @class 简单分页组件（只显示上一页、下一页）
 * @constructor
 * @example
 * @return
 */
Fw.SimplePaging = Fw.extend(Fw.Paging, {
    /**
     * 初始化组件
     */
    initComponent : function() {
        this.ajax = this.owner.ajax;
        this.ajax = Fw.apply(this.ajax, {
            pageLimit: 1
        });
        Fw.SimplePaging.superclass.initComponent.call(this);
    },
    /**
     * 初始化HTML模版
     */
    initTpl : function() {
        var id = this.owner.el.attr('id');
        var colspan = 20;//?
        var tpl = [];
        //
        this.pagingItems = {
            id: id,
            prev: Fw.id(),
            next: Fw.id(),
            displayInfo: Fw.id(),
            colspan : colspan
        };
        //
        tpl.push('<tfoot>');
        tpl.push('<tr>');
        tpl.push('<td id="${id}-paging" class="paging-body" colspan="${colspan}" width="100%" nowrap>');
        ////
        tpl.push('<a id="${next}" page="next" title="下一页" style="width: 30px;">›</a>');
        tpl.push('<a id="${prev}" page="prev" title="上一页" style="width: 30px;">‹</a>');
        tpl.push('<span id="${displayInfo}" class="displayInfo"></span>');
        //
        tpl.push('</td>');
        tpl.push('</tr>');
        tpl.push('</tfoot>');
        this.owner.el.append(Fw.template(tpl, this.pagingItems));
        this.el = $('#' + id + '-paging');
        this.displayInfo = $('#' + this.pagingItems.displayInfo);
        //
        if(!Fw.isTouch){
            this.el.find('[title]').tooltip({
                placement: 'auto'
            });
        }
    },
    /**
     * 更新分页信息 
     */
    update: function(){
        var isEmpty = this.pageData.total === 0;
        var item;
        for(var p in this.pagingItems){
            item = $('#' + this.pagingItems[p]);
            if(!item || !item.attr('page')) continue;
            switch(p) {
                case 'prev':
                    item[this.ajax.currentPage === 1 ? 'addClass' : 'removeClass']('disable');
                    break;
                case 'next':
                    item[isEmpty ? 'addClass' : 'removeClass']('disable');
                    break;
            }
        }
        //
        var msg;
        if(isEmpty){
            msg = this.emptyMsg;
        }
        else{
            msg = '显示 ' + this.pageData.start + ' - ' + this.pageData.end + ' 条';
        }
        this.displayInfo.html(msg);
        //
        this.movePages = false;
    },
    /**
     * 刷新分页信息
     */
    refresh: function(ajax, data){
        var totalCount = data ? data.length : 0;
        var start = ((this.ajax.currentPage - 1) * this.ajax.pageSize) + 1;
        var end = this.ajax.currentPage * this.ajax.pageSize;
        this.pageData = {
            total: totalCount,
            start: start,
            end: totalCount < end ? start + totalCount - 1 : end
        };
        this.update();
    },
    /**
     * 移动到上1页
     */
    movePrevious: function(){
        var prev = -- this.ajax.currentPage;
        if (prev > 0) {
            this.loadPage(prev);
        }
    },
    /**
     * 移动到下1页
     */
    moveNext: function(){
        if(!this.pageData) return;
        this.loadPage(++ this.ajax.currentPage);
    }
});